package com.qing.administer.result;

import cn.dev33.satoken.exception.SaTokenException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;

/**
 * 异常处理
 */
@Slf4j
@RestControllerAdvice
public class MyExceptionHandler {



     @ExceptionHandler(value = Exception.class) // 捕获 Controller 中抛出的指定类型的异常，也可以指定其他异常
    public Object handler(Exception exception,HttpServletRequest request){
//         log.info("进入异常 处理中 ----------------------------------------");
         //去掉统一拦截打的标签，避免进入统一处理返回值方法
         request.removeAttribute(CommonFinal.RESPONSE_RESULT_ANN);

         //记录异常信息
        if (exception instanceof CommonException){  //自定义异常
            CommonException customException = (CommonException) exception;
            log.warn(customException.getCommonEnum().getMessage());
            return ResultInfo.failure(customException.getCommonEnum().getCode(),customException.getCommonEnum().getMessage(),exception.getMessage());
        } else if (exception instanceof NoHandlerFoundException) { //404异常处理
             return ResultInfo.failure(ResultCode.PAGE_NOT_FOUND);
         }else if(exception instanceof SaTokenException){
            log.warn(exception.getMessage());
            return ResultInfo.failure(ResultCode.UNKNOWN_EXCEPTION.getCode(),exception.getMessage());
        } else {  //500异常
            log.error(exception.getMessage());
            return ResultInfo.failure(ResultCode.UNKNOWN_EXCEPTION);
        }

     }


}
